<?php

/**
 * CRYPT - Encryption & Decryption
 * 
 * @author    : Dino (DBK)
 * @version   : 1.0
 * @date      : 20/3/2013
 * 
 */
class Crypt {

  private $_key = 'inno@tweets';

  public function __construct() {
    $this->_key = md5($this->_key);
  }

  public function encrypt($data = NULL) {
    $encrypt = $hexcrypt = NULL;
    $data = (string) trim($data);
    if (empty($data))
      return FALSE;
    $data = base64_encode(urlencode($data));
    $data = $data . str_repeat(chr((16 - (strlen($data) % 16))), (16 - (strlen($data) % 16)));
    $data = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->_key, $data, MCRYPT_MODE_CBC, str_repeat("\0", 16));
    $data = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->_key, $data, MCRYPT_MODE_CBC, str_repeat("\0", 16));
    for ($i = 0; $i < strlen($data); $i++)
      $encrypt .= $data[$i] ^ $this->_key[$i % strlen($this->_key)];
    //$encrypt = base64_encode(urlencode($encrypt));
    for ($i = 0; $i < strlen($encrypt); $i++)
      $hexcrypt .= str_pad(dechex(ord($encrypt[$i])), 2, 0, STR_PAD_LEFT);
    return trim($hexcrypt);
  }

  public function decrypt($hexcrypt = NULL) {
    $crypt = $data = NULL;
    $hexcrypt = (string) trim($hexcrypt);
    if (preg_match('/\W/', $hexcrypt))
      return FALSE;
    for ($i = 0; $i < strlen($hexcrypt); $i+=2)
      $crypt .= chr(hexdec(substr($hexcrypt, $i, 2)));
    //$crypt = urldecode(base64_decode($crypt, TRUE));
    for ($i = 0; $i < strlen($crypt); $i++)
      $data .= $crypt[$i] ^ $this->_key[$i % strlen($this->_key)];
    $data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->_key, $data, MCRYPT_MODE_CBC, str_repeat("\0", 16));
    $data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->_key, $data, MCRYPT_MODE_CBC, str_repeat("\0", 16));
    $data = substr($data, 0, -ord($data[strlen($data) - 1]));
    $data = urldecode(base64_decode($data, TRUE));
    return trim($data);
  }

  public function __destruct() {
    unset($this->_key);
  }

}

?>
